# _*_ coding: utf-8 _*_
"""
Time:     2024/9/4
Author:   2051261
File:     cli.py
"""
from __future__ import annotations
import typing as t
import logging
import threading
import shutil
import click
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
from mine.scheduler.scheduler import run
from extractor.init import get_default_paths
from extractor.init import init
from extractor.config.load import read_yml
from extractor.config.check_yml import check_task_yml
from extractor.const import ENV
from extractor.config.load import add_scheduler_job


logger = logging.getLogger(__name__)

current_path = Path(__file__).resolve()


if t.TYPE_CHECKING:
    from extractor.flow.task_entry import TaskEntry


def execute_immediate_tasks(is_run_task: list[TaskEntry]):
    """在后台线程中运行立即执行的任务"""
    max_workers = 5
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(task.run): task for task in is_run_task}

        for future in as_completed(futures):
            task = futures[future]
            _ = future.result()  # 阻塞直到该任务完成
            add_scheduler_job(task)  # 立即执行添加任务

    # # 所有立即执行的任务完成后，注册定时任务
    # for task in is_run_task:
    #     add_scheduler_job(task)


async def run_task():
    """Run schedule tasks"""
    is_run_task = await init()
    for task in is_run_task:
        task.run()

    # threading.Thread(target=execute_immediate_tasks, args=(is_run_task,), daemon=True).start()
    # run()

